from service.setting_service import DataDictionaryService
from views.common.translator import Translator
from views.template_page_view import BasePageTemplateView, FormItemDto


class CommonSettingView(BasePageTemplateView):

    def __init__(self, parent=None):
        t = Translator()
        super().__init__("CommonSettingView", parent=parent)

        form_items = [
            FormItemDto("总资金量", "setting.stock.money.all", "100000", "int"),
            FormItemDto("Tushare Token", "setting.app.tushare.token", "", "text"),
        ]

        # 添加一个报表
        self.addFromTemplate(form_items, "基础配置表单", self.commonSettingCallback)

    def commonSettingCallback(form_data: list[FormItemDto]):
        print("Form Data:", form_data)
        """
        接收 FormItemDto 列表并保存到数据库。
        """

        dataMap = DataDictionaryService()
        for item in form_data:
            # 调用 DataDictionaryService 的保存方法
            try:
                dataMap.add_dictionary_item(
                    key=item.form_key, value=item.form_value, desc=item.form_desc
                )
                print(f"Saved field: {item.form_key} - {item.form_value}")
            except Exception as e:
                print(f"Failed to save field {item.form_key}. Error: {e}")
